package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.qo.JSONResult;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext act;
    @Override
    public List<Permission> selectAll() {

        return permissionMapper.listAll();

    }

    @Override
    public void deleteById(Long id) {
        permissionMapper.deleteById(id);
    }

    @Override
    public void insertbatch(List<Permission> permissionList) {
        permissionMapper.insertbatch(permissionList);
    }

    @Override
    public List<String> listAllExpression() {
        return permissionMapper.listAllExpression();
    }

    @Override
    public void reload() {
        Map<String, Object> beansMap = act.getBeansWithAnnotation(Controller.class);
        //获取values
        Collection<Object> values = beansMap.values();
        List<Permission> permissionList=new ArrayList<Permission>();
        List<String> existExpressionList=permissionMapper.listAllExpression();
        //遍历values，获取每个类的所有方法
        for (Object o:values
        ) {
            Method[] methods = o.getClass().getDeclaredMethods();
            //遍历方法，打印方法中注解的属性
            for (Method m:methods
            ) {
                RequiredPermission annotation = m.getAnnotation(RequiredPermission.class);
                if(annotation!=null)
                {
                    System.out.println(annotation.name()+"="+annotation.expression());
                    Permission permission=new Permission();
                    permission.setName(annotation.name());
                    permission.setExpression(annotation.expression());
                    if(!existExpressionList.contains(annotation.expression())) {
                        permissionList.add(permission);
                    }
                }
            }
        }
        if(permissionList.size()>0) {
            permissionMapper.insertbatch(permissionList);

        }

    }
}
